package com.kedacom.ctsp.authz.security.provider;

import com.kedacom.ctsp.authz.security.AuthzSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.kedacom.ctsp.authz.security.util.Constant.REQ_ATTR_TOKEN;
import static com.kedacom.ctsp.authz.security.util.Constant.REQ_HEADER_TOKEN;

/**
 * @author xuwei
 */
@Slf4j
public class TokenLoginFilter extends OncePerRequestFilter {

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private AuthzSecurityProperties securityProperties;

    /**
     * 是否需要过滤
     *
     * @param url
     * @return
     */
    private boolean isInclude(String url) {
        Matcher matcher = Pattern.compile(securityProperties.getLoginTokenUrl()).matcher(url);
        return matcher.matches();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String clientToken = request.getHeader(REQ_HEADER_TOKEN);
        if (StringUtils.isNotBlank(clientToken) && tokenManager.validateToken(clientToken)) {
            request.setAttribute(REQ_ATTR_TOKEN, clientToken);
            tokenManager.loginByCurrentToken(clientToken);
        }
        filterChain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return isInclude(request.getServletPath());
    }
}